"use client";
import React, { useEffect, useState } from "react";
import {
  Button,
  Form,
  Input,
  Table,
  TableProps,
  Tooltip,
  Space,
  Pagination,
  message,
} from "antd";
import { SearchOutlined, RestOutlined, LogoutOutlined } from "@ant-design/icons";
import { list, forceLogout } from "@/clientApi/system/monitor/online";
import { useConfirmModal } from "@/utils/ConfirmModal";
import useResponsiveLayout from "@/utils/useResponsiveLayout";

const OnlineView: React.FC = () => {
  const { confirm } = useConfirmModal();
  // 初始查询参数
  const initialQueryParams = {
    pageNum: 1,
    pageSize: 10,
    ipaddr: undefined,
    userName: undefined,
  };

  // 定义表格数据类型
  interface DataType {
    tokenId: string;
    userName: string;
    ipaddr: string;
    loginTime: string;
    key: string;
  }

  // 表单实例
  const [form] = Form.useForm();
  // 表格数据相关状态
  const [dataList, setDataList] = useState<DataType[]>([]);
  const [total, setTotal] = useState(0);
  const [loading, setLoading] = useState(true);
  // 查询参数状态
  const [queryParams, setQueryParams] = useState(initialQueryParams);

  // 表格列配置
  const columns: TableProps<DataType>["columns"] = [
    {
      title: "序号",
      align: "center",
      render: (_: any, __: any, index: number) => {
        return (queryParams.pageNum - 1) * queryParams.pageSize + index + 1;
      },
    },
    {
      title: "会话编号",
      dataIndex: "tokenId",
      key: "tokenId",
      align: "center",
      ellipsis: true,
    },
    {
      title: "登录名称",
      dataIndex: "userName",
      key: "userName",
      align: "center",
      ellipsis: true,
    },
    {
      title: "主机",
      dataIndex: "ipaddr",
      key: "ipaddr",
      align: "center",
      ellipsis: true,
    },
    {
      title: "登录时间",
      dataIndex: "loginTime",
      key: "loginTime",
      align: "center",
      width: 180,
    },
    {
      title: "操作",
      key: "action",
      align: "center",
      render: (_: any, record: DataType) => (
        <Space size="middle">
          <Tooltip title="强退">
            <Button
              type="link"
              size="small"
              icon={<LogoutOutlined />}
              onClick={() => handleForceLogout(record)}
            >
              强退
            </Button>
          </Tooltip>
        </Space>
      ),
    },
  ];

  // 页面加载时获取列表数据
  useEffect(() => {
    getList();
  }, [queryParams]);

  /** 查询在线用户列表 */
  const getList = () => {
    setLoading(true);
    list(queryParams)
      .then((res: any) => {
        setDataList(
          res.rows.map((item: any) => ({
            ...item,
            key: item.tokenId, // 用会话编号作为唯一key
          }))
        );
        setTotal(res.total);
      })
      .finally(() => {
        setLoading(false);
      });
  };

  /** 搜索按钮操作 */
  const handleSearch = () => {
    form.validateFields().then((values) => {
      setQueryParams({
        ...initialQueryParams, // 重置页码
        ipaddr: values.ipaddr,
        userName: values.userName,
      });
    });
  };

  /** 重置按钮操作 */
  const resetSearch = () => {
    form.resetFields();
    setQueryParams(initialQueryParams);
  };

  /** 分页变化处理 */
  const handleTableChange = (page: number, pageSize: number) => {
    setQueryParams({
      ...queryParams,
      pageNum: page,
      pageSize: pageSize,
    });
  };

  /** 强退操作 */
  const handleForceLogout = (record: DataType) => {
    confirm({
      title: "系统提示",
      content: `是否确认强退名称为"${record.userName}"的用户？`,
      onOk() {
         forceLogout(record.tokenId).then(() => {
           message.success("强退成功");
           getList(); // 刷新列表
         });
      },
    });
  };

  return (
    <div className="app-container" style={{ padding: "20px" }}>
      {/* 查询表单 */}
      <Form
        form={form}
        layout={useResponsiveLayout("inline")}
        style={{ marginBottom: 16 }}
        initialValues={{
          ipaddr: undefined,
          userName: undefined,
        }}
      >
        <Form.Item name="ipaddr" label="登录地址">
          <Input placeholder="请输入登录地址" allowClear />
        </Form.Item>
        <Form.Item name="userName" label="用户名称">
          <Input placeholder="请输入用户名称" allowClear />
        </Form.Item>
        <Form.Item>
          <Button
            type="primary"
            icon={<SearchOutlined />}
            size="small"
            onClick={handleSearch}
          >
            搜索
          </Button>
          <Button
            icon={<RestOutlined />}
            size="small"
            style={{ marginLeft: 8 }}
            onClick={resetSearch}
          >
            重置
          </Button>
        </Form.Item>
      </Form>

      {/* 数据表格 */}
      <Table<DataType>
        columns={columns}
        dataSource={dataList}
        loading={loading}
        pagination={false} // 关闭内置分页，使用自定义分页
        rowKey="tokenId"
        style={{ width: "100%" }}
      />

      {/* 自定义分页组件 */}
      {total > 0 && (
        <Pagination
          current={queryParams.pageNum}
          pageSize={queryParams.pageSize}
          total={total}
          showSizeChanger
          showQuickJumper
          showTotal={(total) => `共 ${total} 条记录`}
          pageSizeOptions={["10", "20", "50", "100"]}
          onChange={handleTableChange}
          style={{ marginTop: 16, textAlign: "right" }}
        />
      )}
    </div>
  );
};

export default OnlineView;